package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import webserver.Control;

public class GUI {
	private JFrame frame;
	private MyLayeredPane logLayeredPane;

	private JComboBox box = null;
	private JTextField portText = null;
	private JTextField contentBaseText = null;

	public GUI() {
		frame = new JFrame("Diagnostic Webserver");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setBounds(0, 0, 800, 600);

		createControls();

		logLayeredPane = new MyLayeredPane();
		logLayeredPane.setPreferredSize(new Dimension(800, 600));
		logLayeredPane.setBorder(BorderFactory.createTitledBorder("Log"));
		frame.add(logLayeredPane, BorderLayout.CENTER);
		
		frame.setVisible(true);

	}

	private void createControls() {
		JPanel controls = new JPanel();
		controls.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
		controls.setBorder(BorderFactory.createTitledBorder("Controls"));
		controls.setPreferredSize(new Dimension(800, 60));

		controls.add(new JLabel("host"));
		box = new JComboBox(Control.getInstance()
				.getPossibleHosts());
		controls.add(box);

		controls.add(new JLabel("port"));
		portText = new JTextField(5);
		controls.add(portText);

		controls.add(new JLabel("contentbase"));
		contentBaseText = new JTextField(20);
		controls.add(contentBaseText);

		JButton startButton = new JButton("start");
		startButton.setBackground(Color.GREEN);
		startButton.setOpaque(true);
		startButton.addActionListener(Control.getInstance());
		controls.add(startButton);

		frame.add(controls, BorderLayout.NORTH);
	}

	public String getHost(){
		return (String) box.getSelectedItem();
	}
	
	public int getPort() {
		int port = 0;
		
		try {
			port = Integer.parseInt(portText.getText());
		} catch (NumberFormatException ex) {
			port = -1;
		}

		return port;
	}

	public MyJTextPane getTextPaneForID(int id) {
		MyJScrollPane logPane = logLayeredPane.getLayer(id);
		if (logPane == null) {
			logPane = logLayeredPane.addInLayer(id);
			System.out.println(logPane);
		}
		
		return logPane.getTextPane();
	}
	
	public void removeLayer(int id) {
		logLayeredPane.removeLayer(id);
	}
	
	public File getContentBase() {
		return new File(contentBaseText.getText());
	}
}
